import React, { Component,Fragment } from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import { authRoutes } from 'routes'
import MLayout from 'components/Layout'
import { connect } from 'react-redux'
import NotFound from '../NotFound/index.js'
class Admin extends Component {
	
	render() {
		return (
			<Fragment>
				<MLayout>
					<Switch>
						{
							authRoutes.map(route=>{
								return (
									<Route
										key={route.path}
										path={route.path}
										render = {
                      (routeParams)=>{
                        /* 
                        判断有无token 
                        */
                       
                        if(this.props.token){
                          /* 
                          判断 用户角色
                          */
                        
                         // 判断角色
                         if(route.meta.roles === "*" || route.meta.roles.some(role=> role === this.props.role ) ){
                           // 说明当前角色可以访问
                           return <route.component {...routeParams} />
                         }else{
                           // 当前角色 不能访问 重定向到 noPerssion
                           return <Redirect to="/admin/noPerssion"/>
                         }
                         
                        }else{
                          this.props.history.push({
                            pathname:'/login',
                            state: {
                              from: route.path
                            }
                          })
                        }
                      }
                    }
									/>
								)
							})
						}
            <Route path="/admin/404" component={ NotFound  }/>
						<Redirect to="/admin/dashboard" from="/admin" exact/>
						<Redirect to="/admin/404" />
					</Switch>
				</MLayout>
			</Fragment>
		)
	}
}
const mapStateToProps = (state)=>{
  return {
    token: state.user.token,
    role: state.user.userInfo.role
  }
}
export default connect(mapStateToProps)(Admin)